const { formatTime } = require('../../utils/util.js')
const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    userId: null,
    userInfo: null,
    loading: true,
    isBioExpanded: false,
    statusBarHeight: 0, // 添加状态栏高度
    isFollowing: false,  // 添加关注状态
    currentUserId: null  // 添加当前用户ID
  },

  onLoad(options) {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    })

    // 设置当前用户ID
    const currentUser = wx.getStorageSync('userInfo')
    if (currentUser) {
      this.setData({ currentUserId: currentUser.id })
    }

    // console.log('User page options:', options) // 调试用
    if (options.id) {
      this.setData({ userId: options.id })
      this.loadUserInfo()
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 点击发消息按钮
  onTapMessage() {
    const targetUser = this.data.userInfo
    if (!targetUser) return

    wx.navigateTo({
      url: `/pages/chat/chat?targetUserId=${targetUser.id}&targetName=${encodeURIComponent(targetUser.username || '未知用户')}`
    })
  },

  // 预览头像
  previewAvatar() {
    const avatar = this.data.userInfo?.avatar
    if (!avatar) return
    
    wx.previewImage({
      urls: [avatar]
    })
  },

  // 展开/收起简介
  toggleBio() {
    this.setData({
      isBioExpanded: !this.data.isBioExpanded
    })
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadUserInfo()
    wx.stopPullDownRefresh()
  },

  // 加载用户信息
  async loadUserInfo() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/user/info/${this.data.userId}`),
          method: 'GET',
          success: (res) => {
            resolve(res)
          },
          fail: reject
        })
      })

      if (res.data && res.data.code === 200) {
        const userInfo = res.data.data
        // 格式化时间
        userInfo.createTime = formatTime(new Date(userInfo.createTime))
        console.log(userInfo)
        // 映射字段名称以匹配我们的UI
        const mappedUserInfo = {
          ...userInfo,
          // 使用后端返回的字段映射到我们的UI字段
          postsCount: userInfo.myPublish || 0,
          likesCount: userInfo.myPraised || 0,
          collectionsCount: userInfo.myCollection || 0,
          followersCount: userInfo.myFans || 0,
          followingCount: userInfo.myFollows || 0
        }
        
        this.setData({
          userInfo: mappedUserInfo,
          loading: false
        })

        // 设置导航栏标题
        wx.setNavigationBarTitle({
          title: mappedUserInfo.username + '的主页'
        })
        
        // 检查是否已关注该用户
        this.checkFollowStatus()
      } else {
        throw new Error(res.data.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('Load user info failed:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },
  
  // 检查关注状态
  async checkFollowStatus() {
    const currentUser = wx.getStorageSync('userInfo')
    if (!currentUser || !this.data.userInfo) return
    
    // 如果是自己的主页，不显示关注按钮
    if (currentUser.id === this.data.userInfo.id) {
      return
    }
    
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/user/follow/check/${currentUser.id}/${this.data.userInfo.id}`),
          method: 'GET',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })
      
      if (res.data && res.data.code === 200) {
        this.setData({ isFollowing: res.data.data })
      }
    } catch (error) {
      console.error('Check follow status failed:', error)
    }
  },
  
  // 关注/取消关注
  async onTapFollow() {
    const currentUser = wx.getStorageSync('userInfo')
    if (!currentUser || !this.data.userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    // 如果是自己的主页，不能关注自己
    if (currentUser.id === this.data.userInfo.id) {
      wx.showToast({
        title: '不能关注自己',
        icon: 'none'
      })
      return
    }
    
    const followerId = currentUser.id
    const followedId = this.data.userInfo.id
    
    try {
      if (this.data.isFollowing) {
        // 取消关注
        await this.unfollowUser(followerId, followedId)
      } else {
        // 关注
        await this.followUser(followerId, followedId)
      }
    } catch (error) {
      console.error('Follow/Unfollow failed:', error)
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      })
    }
  },
  
  // 关注用户
  async followUser(followerId, followedId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/user/follow/${followerId}/${followedId}`),
          method: 'POST',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })
      
      if (res.data && res.data.code === 200) {
        this.setData({ isFollowing: true })
        
        // 更新关注者数量
        if (this.data.userInfo) {
          const userInfo = { ...this.data.userInfo }
          userInfo.followersCount = (userInfo.followersCount || 0) + 1
          this.setData({ userInfo })
        }
        
        wx.showToast({
          title: '关注成功',
          icon: 'success'
        })
      } else {
        throw new Error(res.data.message || '关注失败')
      }
    } catch (error) {
      console.error('Follow user failed:', error)
      throw error
    }
  },
  
  // 取消关注
  async unfollowUser(followerId, followedId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/user/follow/${followerId}/${followedId}`),
          method: 'DELETE',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })
      
      if (res.data && res.data.code === 200) {
        this.setData({ isFollowing: false })
        
        // 更新关注者数量
        if (this.data.userInfo) {
          const userInfo = { ...this.data.userInfo }
          userInfo.followersCount = Math.max((userInfo.followersCount || 0) - 1, 0)
          this.setData({ userInfo })
        }
        
        wx.showToast({
          title: '已取消关注',
          icon: 'success'
        })
      } else {
        throw new Error(res.data.message || '取消关注失败')
      }
    } catch (error) {
      console.error('Unfollow user failed:', error)
      throw error
    }
  }
})
